<!-- views/system/OperationLogs.vue -->
<template>
  <div class="operation-logs-management">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="header-left">
        <h1 class="page-title">操作日志</h1>
        <div class="status-badges">
          <el-tag type="primary" class="total-badge">
            <el-icon><Document /></el-icon>
            总日志: {{ stats.totalLogs }}
          </el-tag>
          <el-tag type="success" class="today-badge">
            <el-icon><Calendar /></el-icon>
            今日日志: {{ stats.todayLogs }}
          </el-tag>
          <el-tag type="warning" class="warning-badge">
            <el-icon><Warning /></el-icon>
            警告日志: {{ stats.warningLogs }}
          </el-tag>
          <el-tag type="danger" class="error-badge">
            <el-icon><CircleClose /></el-icon>
            错误日志: {{ stats.errorLogs }}
          </el-tag>
        </div>
      </div>
      
      <div class="header-actions">
        <!-- 导出日志 -->
        <el-button 
          :icon="Download" 
          @click="exportLogs"
        >
          导出日志
        </el-button>
        
        <!-- 清理日志 -->
        <el-button 
          :icon="Delete" 
          @click="showCleanupDialog"
        >
          清理日志
        </el-button>
        
        <!-- 刷新数据 -->
        <el-button 
          :icon="Refresh" 
          @click="loadLogs"
          :loading="loading"
        >
          刷新
        </el-button>
      </div>
    </div>

    <!-- 统计概览 -->
    <el-row :gutter="16" class="stats-row">
      <el-col :xs="24" :sm="6">
        <MetricCard
          title="今日操作数"
          :value="stats.todayOperations"
          :icon="Edit"
          color="#1890ff"
          :trend="stats.operationTrend"
        />
      </el-col>
      <el-col :xs="24" :sm="6">
        <MetricCard
          title="用户活跃度"
          :value="stats.userActivityRate"
          suffix="%"
          :icon="User"
          color="#52c41a"
          :trend="stats.activityTrend"
        />
      </el-col>
      <el-col :xs="24" :sm="6">
        <MetricCard
          title="系统性能"
          :value="stats.systemPerformance"
          suffix="ms"
          :icon="Timer"
          color="#fa8c16"
          :trend="stats.performanceTrend"
        />
      </el-col>
      <el-col :xs="24" :sm="6">
        <MetricCard
          title="安全事件"
          :value="stats.securityEvents"
          :icon="Warning"
          color="#f5222d"
          :trend="stats.securityTrend"
        />
      </el-col>
    </el-row>

    <!-- 筛选条件 -->
    <el-card class="filter-card" shadow="never">
      <el-form :model="queryParams" inline>
        <el-form-item label="操作类型">
          <el-select v-model="queryParams.operationType" clearable placeholder="全部类型" style="width: 150px">
            <el-option label="创建" value="create" />
            <el-option label="更新" value="update" />
            <el-option label="删除" value="delete" />
            <el-option label="查询" value="query" />
            <el-option label="登录" value="login" />
            <el-option label="导出" value="export" />
          </el-select>
        </el-form-item>
        
        <el-form-item label="操作状态">
          <el-select v-model="queryParams.operationStatus" clearable placeholder="全部状态" style="width: 120px">
            <el-option label="成功" value="success" />
            <el-option label="失败" value="failed" />
            <el-option label="警告" value="warning" />
          </el-select>
        </el-form-item>
        
        <el-form-item label="操作用户">
          <el-input
            v-model="queryParams.operator"
            placeholder="输入用户名"
            clearable
            style="width: 150px"
          />
        </el-form-item>
        
        <el-form-item label="操作模块">
          <el-select v-model="queryParams.module" clearable placeholder="全部模块" style="width: 150px">
            <el-option label="用户管理" value="users" />
            <el-option label="角色权限" value="roles" />
            <el-option label="系统设置" value="settings" />
            <el-option label="数据管理" value="data" />
            <el-option label="对账管理" value="reconciliation" />
          </el-select>
        </el-form-item>
        
        <el-form-item label="操作时间">
          <el-date-picker
            v-model="queryParams.operationDateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
        
        <el-form-item>
          <el-button type="primary" :icon="Search" @click="handleSearch">
            查询
          </el-button>
          <el-button :icon="Refresh" @click="handleReset">
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 日志列表 -->
    <el-card class="table-card">
      <template #header>
        <div class="table-header">
          <span>操作日志列表</span>
          <div class="table-actions">
            <el-button-group>
              <el-button :icon="Sort" @click="handleSort('created_at')">
                按时间
              </el-button>
              <el-button :icon="Sort" @click="handleSort('user')">
                按用户
              </el-button>
            </el-button-group>
          </div>
        </div>
      </template>

      <el-table
        ref="logTableRef"
        :data="tableData"
        v-loading="loading"
        @selection-change="handleSelectionChange"
        @row-click="viewLogDetail"
        @sort-change="handleSortChange"
        class="logs-table"
        row-key="id"
      >
        <el-table-column type="selection" width="50" />
        
        <!-- 操作时间 -->
        <el-table-column prop="createdAt" label="操作时间" width="180" sortable fixed>
          <template #default="{ row }">
            <div class="time-cell">
              <div class="date">{{ formatDate(row.createdAt) }}</div>
              <div class="time">{{ formatTime(row.createdAt) }}</div>
            </div>
          </template>
        </el-table-column>
        
        <!-- 操作用户 -->
        <el-table-column prop="userName" label="操作用户" width="120" />
        
        <!-- 操作模块 -->
        <el-table-column prop="module" label="操作模块" width="120" />
        
        <!-- 操作类型 -->
        <el-table-column prop="action" label="操作类型" width="100">
          <template #default="{ row }">
            <el-tag :type="getActionType(row.action)">
              {{ getActionText(row.action) }}
            </el-tag>
          </template>
        </el-table-column>
        
        <!-- 操作描述 -->
        <el-table-column prop="description" label="操作描述" min-width="200" />
        
        <!-- 操作状态 -->
        <el-table-column prop="status" label="操作状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getStatusType(row.status)">
              {{ getStatusText(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        
        <!-- IP地址 -->
        <el-table-column prop="ip" label="IP地址" width="130" />
        
        <!-- 操作 -->
        <el-table-column label="操作" width="100" fixed="right">
          <template #default="{ row }">
            <el-button 
              size="small" 
              type="primary" 
              @click.stop="viewLogDetail(row)"
            >
              查看详情
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <el-pagination
        v-model:current-page="pagination.page"
        v-model:page-size="pagination.limit"
        :page-sizes="[10, 20, 50, 100]"
        :total="pagination.total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        class="table-pagination"
      />
    </el-card>

    <!-- 日志详情抽屉 -->
    <el-drawer
      v-model="detailDrawerVisible"
      title="日志详情"
      direction="rtl"
      size="600px"
    >
      <div class="log-detail" v-if="detailLog">
        <el-descriptions :column="1" border>
          <el-descriptions-item label="日志ID">{{ detailLog.id }}</el-descriptions-item>
          <el-descriptions-item label="操作时间">{{ formatDateTime(detailLog.createdAt) }}</el-descriptions-item>
          <el-descriptions-item label="操作用户">{{ detailLog.userName }}</el-descriptions-item>
          <el-descriptions-item label="操作模块">{{ detailLog.module }}</el-descriptions-item>
          <el-descriptions-item label="操作类型">
            <el-tag :type="getActionType(detailLog.action)">
              {{ getActionText(detailLog.action) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="操作描述">{{ detailLog.description }}</el-descriptions-item>
          <el-descriptions-item label="操作状态">
            <el-tag :type="getStatusType(detailLog.status)">
              {{ getStatusText(detailLog.status) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="IP地址">{{ detailLog.ip }}</el-descriptions-item>
          <el-descriptions-item label="User Agent">{{ detailLog.userAgent }}</el-descriptions-item>
          <el-descriptions-item label="请求数据" v-if="detailLog.requestData">
            <pre class="data-preview">{{ detailLog.requestData }}</pre>
          </el-descriptions-item>
          <el-descriptions-item label="响应数据" v-if="detailLog.responseData">
            <pre class="data-preview">{{ detailLog.responseData }}</pre>
          </el-descriptions-item>
        </el-descriptions>
      </div>
    </el-drawer>

    <!-- 清理日志对话框 -->
    <el-dialog
      v-model="cleanupDialogVisible"
      title="清理日志"
      width="500px"
    >
      <el-form :model="cleanupParams" label-width="100px">
        <el-form-item label="保留时间">
          <el-select v-model="cleanupParams.keepDays" placeholder="请选择保留时间">
            <el-option label="保留7天" :value="7" />
            <el-option label="保留30天" :value="30" />
            <el-option label="保留90天" :value="90" />
            <el-option label="保留180天" :value="180" />
            <el-option label="保留1年" :value="365" />
          </el-select>
        </el-form-item>
        
        <el-form-item label="日志类型">
          <el-checkbox-group v-model="cleanupParams.logTypes">
            <el-checkbox value="success">成功日志</el-checkbox>
            <el-checkbox value="failed">失败日志</el-checkbox>
            <el-checkbox value="warning">警告日志</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
        
        <el-alert
          title="注意：清理操作不可恢复，请谨慎操作"
          type="warning"
          show-icon
        />
      </el-form>
      
      <template #footer>
        <el-button @click="cleanupDialogVisible = false">取消</el-button>
        <el-button 
          type="primary" 
          @click="performCleanup"
          :loading="cleaningUp"
        >
          确定清理
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from '@vue/runtime-core'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  Document, Calendar, Warning, CircleClose, Download, Delete, Refresh, Search, Sort,
  Edit, User, Timer
} from '@element-plus/icons-vue'
import { useAppStore } from '@/stores/appStore'
import MetricCard from '@/views/dashboard/components/MetricCard.vue'
import { systemAPI } from '@/api/system'

// Store
const appStore = useAppStore()

// 类型定义
interface LogItem {
  id: number
  userId: number
  userName: string
  action: string
  module: string
  description?: string
  ip?: string
  userAgent?: string
  requestData?: string
  responseData?: string
  status: string
  createdAt: string
}

// 响应式数据
const logTableRef = ref()
const loading = ref(false)
const cleaningUp = ref(false)

const selectedLogs = ref<any[]>([])
const tableData = ref<LogItem[]>([])
const pagination = reactive({
  page: 1,
  limit: 20,
  total: 0
})

// 对话框相关
const detailDrawerVisible = ref(false)
const cleanupDialogVisible = ref(false)

// 详情数据
const detailLog = ref<LogItem>({
  id: 0,
  userId: 0,
  userName: '',
  action: '',
  module: '',
  description: '',
  ip: '',
  userAgent: '',
  requestData: '',
  responseData: '',
  status: '',
  createdAt: ''
})

const currentLog = ref<LogItem>({
  id: 0,
  userId: 0,
  userName: '',
  action: '',
  module: '',
  description: '',
  ip: '',
  userAgent: '',
  requestData: '',
  responseData: '',
  status: '',
  createdAt: ''
})

// 清理参数
const cleanupParams = ref({
  keepDays: 30,
  logTypes: ['success', 'failed', 'warning']
})

// 查询参数
const queryParams = reactive({
  page: 1,
  limit: 20,
  action: '',
  status: '',
  operator: '',
  module: '',
  startDate: '',
  endDate: ''
})

// 统计信息
const stats = reactive({
  totalLogs: 0,
  todayLogs: 0,
  warningLogs: 0,
  errorLogs: 0,
  todayOperations: 0,
  userActivityRate: 0,
  systemPerformance: 0,
  securityEvents: 0,
  operationTrend: 0,
  activityTrend: 0,
  performanceTrend: 0,
  securityTrend: 0
})

// 方法
const loadLogs = async () => {
  loading.value = true
  try {
    const params = {
      page: pagination.page,
      limit: pagination.limit,
      action: queryParams.action,
      status: queryParams.status,
      userId: queryParams.operator ? parseInt(queryParams.operator) : undefined,
      module: queryParams.module,
      startDate: queryParams.startDate,
      endDate: queryParams.endDate
    }
    
    const response = await systemAPI.getOperationLogs(params)
    
    if (response.data && response.data.list) {
      tableData.value = response.data.list
      pagination.total = response.data.pagination.total
    }
  } catch (error: any) {
    console.error('加载日志数据失败:', error)
    ElMessage.error('加载日志数据失败: ' + (error.message || '未知错误'))
  } finally {
    loading.value = false
  }
}

const loadStats = async () => {
  // 这里可以调用获取统计信息的API
  // 暂时使用模拟数据
  stats.totalLogs = 1280
  stats.todayLogs = 45
  stats.warningLogs = 12
  stats.errorLogs = 3
  stats.todayOperations = 128
  stats.userActivityRate = 85
  stats.systemPerformance = 120
  stats.securityEvents = 2
  stats.operationTrend = 5
  stats.activityTrend = 2.3
  stats.performanceTrend = -1.2
  stats.securityTrend = 0.8
}

const handleSearch = () => {
  pagination.page = 1
  loadLogs()
}

const handleReset = () => {
  Object.assign(queryParams, {
    page: 1,
    limit: 20,
    action: '',
    status: '',
    operator: '',
    module: '',
    startDate: '',
    endDate: ''
  })
  loadLogs()
}

const handleSelectionChange = (selection: any[]) => {
  selectedLogs.value = selection
}

const handleSizeChange = (val: number) => {
  pagination.limit = val
  pagination.page = 1
  loadLogs()
}

const handleCurrentChange = (val: number) => {
  pagination.page = val
  loadLogs()
}

const handleSort = (field: string) => {
  // 排序逻辑可以根据需要实现
  loadLogs()
}

const handleSortChange = ({ prop, order }: any) => {
  // 排序逻辑可以根据需要实现
  loadLogs()
}

const viewLogDetail = (log: LogItem) => {
  detailLog.value = { ...log }
  detailDrawerVisible.value = true
}

const exportLogs = async () => {
  try {
    // 实现导出日志的逻辑
    ElMessage.success('日志导出成功')
  } catch (error: any) {
    ElMessage.error('日志导出失败: ' + (error.message || '未知错误'))
  }
}

const showCleanupDialog = () => {
  cleanupDialogVisible.value = true
}

const performCleanup = async () => {
  try {
    cleaningUp.value = true
    // 实现清理日志的逻辑
    ElMessage.success('日志清理成功')
    cleanupDialogVisible.value = false
  } catch (error: any) {
    ElMessage.error('日志清理失败: ' + (error.message || '未知错误'))
  } finally {
    cleaningUp.value = false
  }
}

// 工具函数
const formatDate = (dateString: string) => {
  if (!dateString) return ''
  const date = new Date(dateString)
  return date.toLocaleDateString('zh-CN')
}

const formatTime = (dateString: string) => {
  if (!dateString) return ''
  const date = new Date(dateString)
  return date.toLocaleTimeString('zh-CN', {
    hour: '2-digit',
    minute: '2-digit'
  })
}

const formatDateTime = (dateString: string) => {
  if (!dateString) return ''
  const date = new Date(dateString)
  return date.toLocaleString('zh-CN')
}

const getActionType = (action: string) => {
  const typeMap: Record<string, any> = {
    create: 'success',
    update: 'primary',
    delete: 'danger',
    query: 'info',
    login: 'warning',
    export: 'success'
  }
  return typeMap[action] || 'info'
}

const getActionText = (action: string) => {
  const textMap: Record<string, string> = {
    create: '创建',
    update: '更新',
    delete: '删除',
    query: '查询',
    login: '登录',
    export: '导出'
  }
  return textMap[action] || action
}

const getStatusType = (status: string) => {
  const typeMap: Record<string, any> = {
    success: 'success',
    failed: 'danger',
    warning: 'warning'
  }
  return typeMap[status] || 'info'
}

const getStatusText = (status: string) => {
  const textMap: Record<string, string> = {
    success: '成功',
    failed: '失败',
    warning: '警告'
  }
  return textMap[status] || status
}

// 生命周期
onMounted(() => {
  loadLogs()
  loadStats()
})
</script>

<style scoped>
.operation-logs-management {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.header-left {
  flex: 1;
}

.page-title {
  margin: 0 0 12px 0;
  font-size: 24px;
  font-weight: 600;
  color: #1f2d3d;
}

.status-badges {
  display: flex;
  gap: 12px;
  flex-wrap: wrap;
}

.status-badges .el-tag {
  display: flex;
  align-items: center;
  gap: 4px;
  font-weight: 500;
}

.header-actions {
  display: flex;
  gap: 12px;
}

.stats-row {
  margin-bottom: 20px;
}

.filter-card {
  margin-bottom: 20px;
}

.table-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.table-actions {
  display: flex;
  gap: 8px;
}

.logs-table {
  width: 100%;
}

.time-cell {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.date {
  font-weight: 500;
}

.time {
  font-size: 12px;
  color: #606266;
}

.table-pagination {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
  padding: 20px 0;
}

.log-detail {
  padding: 20px;
}

.data-preview {
  white-space: pre-wrap;
  word-wrap: break-word;
  background-color: #f5f7fa;
  padding: 12px;
  border-radius: 4px;
  max-height: 200px;
  overflow-y: auto;
  margin: 0;
}

/* 移动端适配 */
@media (max-width: 767px) {
  .operation-logs-management {
    padding: 12px;
  }
  
  .page-header {
    flex-direction: column;
    gap: 16px;
    align-items: stretch;
  }
  
  .header-left .page-title {
    font-size: 20px;
  }
  
  .header-actions {
    flex-wrap: wrap;
  }
  
  .status-badges {
    justify-content: center;
  }
  
  .stats-row {
    gap: 12px;
  }
  
  .filter-card .el-form {
    flex-wrap: wrap;
  }
  
  .filter-card .el-form-item {
    width: 100%;
    margin-right: 0;
  }
  
  .table-header {
    flex-direction: column;
    gap: 12px;
    align-items: stretch;
  }
  
  .table-actions {
    justify-content: center;
  }
  
  .logs-table .el-table-column--selection,
  .logs-table .el-table__column--selection {
    display: none;
  }
}
</style>